#include "stdio.h"
#include "stdlib.h"


#define	_USER_DEFINE_MEM_	0
///////////////////////////////////MemoryManager////////////////////////////////////////////////////

typedef	unsigned char	u8;
typedef	unsigned short	u16;
typedef	unsigned long	u32;

#if	_USER_DEFINE_MEM_

#ifdef  NULL
#undef  NULL
#define NULL    ((void *)0)
#endif

#define	        POOL_LEN        1024
#define         MIN_MALLOC      16

u8	mem_pool[POOL_LEN];

typedef long    align;

typedef union mem_info{
        struct {
                union mem_info	*next;
                u32		size;
        }s;
        align x;
}mem_info_t;

static mem_info_t base;

/////////////////////////////////////Interface////////////////////////////////////////////////////////
void mem_init(void)
{
	base.s.next = (mem_info_t *)mem_pool;
	base.s.size = 0;
	/* loop list */
	base.s.next->s.next = NULL;
	base.s.next->s.size = POOL_LEN / sizeof(mem_info_t);
}

void *mem_alloc(u32 bytes)
{
	mem_info_t *p, *prev;
	bytes = (bytes + sizeof(mem_info_t) - 1) / sizeof(mem_info_t) + 1;

	prev = &base;
	for (p = base.s.next; p != NULL; prev = p, p = p->s.next) {
		if (p->s.size >= bytes) {
			if (p->s.size == bytes) {
				prev->s.next = p->s.next;
			} else {
				p->s.size -= bytes;
				p += p->s.size;
				p->s.size = bytes;
			}
			return (void *)(p + 1);
		}
	}
	return NULL;
}

void mem_free(void *ptr)
{
	(void)ptr;
	return;
}

static void mem_debug()
{
	mem_info_t *p = base.s.next;
	if (p == &base) {
		printf("--DEBUG--address:%p, size:%u-->\r\n", (void *)0, 0);
		return ;
	}
	for ( ; p != &base; p = p->s.next) {
		printf("--DEBUG--address:%p, size:%u-->", p + 1, p->s.size);
	}

	printf("\r\n");
}
#else
void mem_init()
{

};

void *mem_alloc(u32 bytes)
{
	return malloc(bytes);
}

void mem_free(void *ptr)
{
	free(ptr);
}
#endif
